{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "id": "906e07f6e562"
   },
   "outputs": [],
   "source": [
    "# @title Copyright 2022 The Cirq Developers\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8bbd73c03ac2"
   },
   "source": [
    "# Circuit Transformers"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "25eb74f260d6"
   },
   "source": [
    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://quantumai.google/cirq/transform/transformers\"><img src=\"https://quantumai.google/site-assets/images/buttons/quantumai_logo_1x.png\" />View on QuantumAI</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/main/docs/transform/transformers.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/colab_logo_1x.png\" />Run in Google Colab</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/main/docs/transform/transformers.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/github_logo_1x.png\" />View source on GitHub</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/transform/transformers.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/download_icon_1x.png\" />Download notebook</a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "03d216c7f7b1"
   },
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "846b32703c5c"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    import cirq\n",
    "except ImportError:\n",
    "    print(\"installing cirq...\")\n",
    "    !pip install --quiet cirq\n",
    "    import cirq\n",
    "\n",
    "    print(\"installed cirq.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9d3d49b9ca2a"
   },
   "source": [
    "## What is a Transformer?\n",
    "A transformer in Cirq is any callable that satisfies the `cirq.TRANSFORMER` API, and *transforms* an input circuit into an output circuit.\n",
    "\n",
    "Circuit transformations are often necessary to compile a user-defined circuit to an equivalent circuit that satisfies the constraints necessary to be executable on a specific device or simulator. The compilation process often involves steps like:\n",
    "- Gate Decompositions: Rewrite the circuit using only gates that belong to the device target gateset, i.e. set of gates which the device can execute. \n",
    "- Qubit Mapping and Routing: Map the logic qubits in the input circuit to physical qubits on the device and insert appropriate swap operations such that final circuit respects the hardware topology. \n",
    "- Circuit Optimizations: Perform hardware specific optimizations, like merging and replacing connected components of 1 and 2 operations with more efficient rewrite operations, commuting Z gates through the circuit, aligning gates in moments and more.\n",
    "\n",
    "\n",
    "Cirq provides many out-of-the-box transformers which can be used as individual compilation passes. It also supplies a general framework for users to create their own transformers, by using powerful primitives and by bundling existing transformers together, to enable the compilation of circuits for specific targets. This page covers the available transformers in Cirq, how to use them, and how to write a simple transformer. The [Custom Transformers](./transformers.ipynb) page presents the details on creating more complex custom transformers through primitives and composition."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "KUor1pGZi0Iw"
   },
   "source": [
    "## Built-in Transformers in Cirq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "861ea1ada088"
   },
   "source": [
    "## Overview\n",
    "Transformers that come with cirq can be found in the [`/cirq/transformers`](https://github.com/quantumlib/Cirq/tree/main/cirq-core/cirq/transformers) package.\n",
    "\n",
    "A few notable examples are:\n",
    "*   **`cirq.align_left` / `cirq.align_right`**: Align gates to the left/right of the circuit by sliding them as far as possible along each qubit in the chosen direction.\n",
    "*   **`cirq.defer_measurements`**:  Moves all (non-terminal) measurements in a circuit to the end of circuit by implementing the deferred measurement principle.\n",
    "*   **`cirq.drop_empty_moments`** / **`cirq.drop_negligible_operations`**:  Removes moments that are empty or operations that have very small effects, respectively.\n",
    "*   **`cirq.eject_phased_paulis`**: Pushes X, Y, and PhasedX gates towards the end of the circuit, potentially absorbing Z gates and modifying gates along the way.\n",
    "*   **`cirq.eject_z`**:  Pushes Z gates towards the end of the circuit, potentially adjusting phases of gates that they pass through.\n",
    "*   **`cirq.expand_composite`**:  Uses `cirq.decompose` to expand gates built from other gates (composite gates).\n",
    "*   **`cirq.merge_k_qubit_unitaries`**: Replaces connected components of unitary operations, acting on <= k qubits, with op-tree given by `rewriter(circuit_op)`.\n",
    "*   **`cirq.optimize_for_target_gateset`**: Attempts to convert a circuit into an equivalent circuit using only gates from a given target gateset.\n",
    "*   **`cirq.stratified_circuit`**: Repacks the circuit to ensure that moments only contain operations from the same category.\n",
    "*   **`cirq.synchronize_terminal_measurements`**:  Moves all terminal measurements in a circuit to the final moment, if possible.\n",
    "\n",
    "\n",
    "Below you can see how to implement a transformer pipeline as a function called `optimize_circuit`, which composes a few of the available Cirq transformers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "AqTylIpssdex"
   },
   "outputs": [],
   "source": [
    "def optimize_circuit(circuit, context=None, k=2):\n",
    "    # Merge 2-qubit connected components into circuit operations.\n",
    "    optimized_circuit = cirq.merge_k_qubit_unitaries(\n",
    "        circuit, k=k, rewriter=lambda op: op.with_tags(\"merged\"), context=context\n",
    "    )\n",
    "\n",
    "    # Drop operations with negligible effect / close to identity.\n",
    "    optimized_circuit = cirq.drop_negligible_operations(optimized_circuit, context=context)\n",
    "\n",
    "    # Expand all remaining merged connected components.\n",
    "    optimized_circuit = cirq.expand_composite(\n",
    "        optimized_circuit, no_decomp=lambda op: \"merged\" not in op.tags, context=context\n",
    "    )\n",
    "\n",
    "    # Synchronize terminal measurements to be in the same moment.\n",
    "    optimized_circuit = cirq.synchronize_terminal_measurements(optimized_circuit, context=context)\n",
    "\n",
    "    # Assert the original and optimized circuit are equivalent.\n",
    "    cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(\n",
    "        circuit, optimized_circuit\n",
    "    )\n",
    "\n",
    "    return optimized_circuit\n",
    "\n",
    "\n",
    "q = cirq.LineQubit.range(3)\n",
    "circuit = cirq.Circuit(\n",
    "    cirq.H(q[1]),\n",
    "    cirq.CNOT(*q[1:]),\n",
    "    cirq.H(q[0]),\n",
    "    cirq.CNOT(*q[:2]),\n",
    "    cirq.H(q[1]),\n",
    "    cirq.CZ(*q[:2]),\n",
    "    cirq.H.on_each(*q[:2]),\n",
    "    cirq.CNOT(q[2], q[0]),\n",
    "    cirq.measure_each(*q),\n",
    ")\n",
    "print(\"Original Circuit:\", circuit, sep=\"\\n\")\n",
    "print(\"Optimized Circuit:\", optimize_circuit(circuit), sep=\"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "mu83U5hGzNcH"
   },
   "source": [
    "## Inspecting transformer actions\n",
    "\n",
    "Every transformer in Cirq accepts a `cirq.TransformerContext` instance, which stores common configurable options useful for all transformers. \n",
    "\n",
    "One of the members of transformer context dataclass is `cirq.TransformerLogger` instance. When a logger instance is specified, every cirq transformer logs its action on the input circuit using the given logger instance. The logs can then be inspected to understand the action of each individual transformer on the circuit.\n",
    "\n",
    "Below, you can inspect the action of each transformer in the `optimize_circuit` method defined above. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "1cqUa2Kc0Hni"
   },
   "outputs": [],
   "source": [
    "context = cirq.TransformerContext(logger=cirq.TransformerLogger())\n",
    "optimized_circuit = optimize_circuit(circuit, context)\n",
    "context.logger.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "d646f99aad84"
   },
   "source": [
    "By first using `cirq.merge_k_qubit_unitaries` to turn connected components of the circuit into `cirq.CircuitOperation`s, `cirq.drop_negligible_operations` was able to identify that one of the merged connected components was equivalent to the identity operation and remove it. The remaining steps returned the circuit to a more typical state, expanding intermediate `cirq.CircuitOperation`s and aligning measurements to be terminal measurements."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "kLm-5LHr0YAd"
   },
   "source": [
    "## Support for no-compile tags\n",
    "\n",
    "Cirq also supports tagging operations with no-compile tags such that these tagged operations are ignored when applying transformations on the circuit. This allows users to gain more fine-grained conrol over the compilation process. \n",
    "\n",
    "Any valid tag can be used as a \"no-compile\" tag by adding it to the `tags_to_ignore` field in `cirq.TransformerContext`. When called with a context, cirq transformers will inspect the `context.tags_to_ignore` field and ignore an operation if `op.tags & context.tags_to_ignore` is not empty. \n",
    "\n",
    "Below, you can use no-compile tags when transforming a circuit using the `optimize_circuit` method defined above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "HEhXziehR29V"
   },
   "outputs": [],
   "source": [
    "# Echo pulses inserted in the circuit to prevent dephasing during idling should be ignored.\n",
    "circuit = cirq.Circuit(\n",
    "    cirq.H(q[0]),\n",
    "    cirq.CNOT(*q[:2]),\n",
    "    [\n",
    "        op.with_tags(\"spin_echoes\") for op in [cirq.X(q[0]) ** 0.5, cirq.X(q[0]) ** -0.5]\n",
    "    ],  # the echo pulses\n",
    "    [cirq.CNOT(*q[1:]), cirq.CNOT(*q[1:])],\n",
    "    [cirq.CNOT(*q[:2]), cirq.H(q[0])],\n",
    "    cirq.measure_each(*q),\n",
    ")\n",
    "# Original Circuit\n",
    "print(\"Original Circuit:\", circuit, \"\\n\", sep=\"\\n\")\n",
    "\n",
    "# Optimized Circuit without tags_to_ignore\n",
    "print(\"Optimized Circuit without specifying tags_to_ignore:\")\n",
    "print(optimize_circuit(circuit, k=1), \"\\n\")\n",
    "\n",
    "# Optimized Circuit ignoring operations marked with tags_to_ignore.\n",
    "print(\"Optimized Circuit while ignoring operations marked with tags_to_ignore:\")\n",
    "context = cirq.TransformerContext(tags_to_ignore=[\"spin_echoes\"])\n",
    "print(optimize_circuit(circuit, k=1, context=context), \"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3f3c7851a571"
   },
   "source": [
    "## Support for recursively transforming sub-circuits\n",
    "\n",
    "By default, an operation `op` of type `cirq.CircuitOperation` is considered as a single top-level operation by cirq transformers. As a result, the sub-circuits wrapped inside circuit operations will often be left as it is and a transformer will only modify the top-level circuit. \n",
    "\n",
    "If you wish to recursively run a transformer on every nested sub-circuit wrapped inside a `cirq.CircuitOperation`, you can set `context.deep=True` in the `cirq.TransformerContext` object. Note that tagged circuit operations marked with any of `context.tags_to_ignore` will be ignored even if `context.deep is True`. See the example below for a better understanding. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "994ffb523487"
   },
   "outputs": [],
   "source": [
    "q = cirq.LineQubit.range(2)\n",
    "circuit_op = cirq.CircuitOperation(\n",
    "    cirq.FrozenCircuit(cirq.I.on_each(*q), cirq.CNOT(*q), cirq.I(q[0]).with_tags(\"ignore\"))\n",
    ")\n",
    "circuit = cirq.Circuit(\n",
    "    cirq.I(q[0]), cirq.I(q[1]).with_tags(\"ignore\"), circuit_op, circuit_op.with_tags(\"ignore\")\n",
    ")\n",
    "print(\"Original Circuit:\", circuit, \"\\n\", sep=\"\\n\\n\")\n",
    "\n",
    "context = cirq.TransformerContext(tags_to_ignore=[\"ignore\"], deep=False)\n",
    "print(\"Optimized Circuit with deep=False and tags_to_ignore=['ignore']:\\n\")\n",
    "print(cirq.drop_negligible_operations(circuit, context=context), \"\\n\\n\")\n",
    "\n",
    "context = cirq.TransformerContext(tags_to_ignore=[\"ignore\"], deep=True)\n",
    "print(\"Optimized Circuit with deep=True and tags_to_ignore=['ignore']:\\n\")\n",
    "print(cirq.drop_negligible_operations(circuit, context=context), \"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "521afc8ef6be"
   },
   "source": [
    "The leading identity gate that wasn't tagged was removed from both optimized circuits, but the identity gates within each `cirq.CircuitOperation` were removed if `deep = true` and the `CircuitOperation` wasn't tagged and the identity operation wasn't tagged. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "iIHUZvLRlHFj"
   },
   "source": [
    "## Compiling to NISQ targets: `cirq.CompilationTargetGateset`\n",
    "Cirq's philosophy on compiling circuits for execution on a NISQ target device or simulator is that it would often require running only a handful of individual compilation passes on the input circuit, one after the other.\n",
    "\n",
    "**`cirq.CompilationTargetGateset`** is an abstraction in Cirq to represent such compilation targets as well as the bundles of transformer passes which should be executed to compile a circuit to this target. Cirq has implementations for common target gatesets like `cirq.CZTargetGateset`, `cirq.SqrtIswapTargetGateset` etc.\n",
    "\n",
    "\n",
    "**`cirq.optimize_for_target_gateset`** is a transformer which compiles a given circuit for a `cirq.CompilationTargetGateset` via the following steps:\n",
    "\n",
    "1. Run all `gateset.preprocess_transformers`\n",
    "2. Convert operations using built-in `cirq.decompose` + `gateset.decompose_to_target_gateset`.\n",
    "3. Run all `gateset.postprocess_transformers`\n",
    "\n",
    "\n",
    "The preprocess transformers often includes optimizations like merging connected components of 1/2 qubit unitaries into a single unitary matrix, which can then be replaced with an efficient analytical decomposition as part of step-2. \n",
    "\n",
    "The post-process transformers often includes cleanups and optimizations like dropping negligible operations, \n",
    "converting single qubit rotations into desired form, circuit alignments etc. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "-QFPCdW0qS3R"
   },
   "outputs": [],
   "source": [
    "# Original QFT Circuit on 3 qubits.\n",
    "q = cirq.LineQubit.range(3)\n",
    "circuit = cirq.Circuit(cirq.QuantumFourierTransformGate(3).on(*q), cirq.measure(*q))\n",
    "print(\"Original Circuit:\", circuit, \"\\n\", sep=\"\\n\")\n",
    "\n",
    "# Compile the circuit for CZ Target Gateset.\n",
    "gateset = cirq.CZTargetGateset(allow_partial_czs=True)\n",
    "cz_circuit = cirq.optimize_for_target_gateset(circuit, gateset=gateset)\n",
    "cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(circuit, cz_circuit)\n",
    "print(\"Circuit compiled for CZ Target Gateset:\", cz_circuit, \"\\n\", sep=\"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "b963809fa20b"
   },
   "source": [
    "`cirq.optimize_for_target_gateset` also supports all the features discussed above, using `cirq.TransformerContext`. For example, you can compile the circuit for sqrt-iswap target gateset and inspect action of individual transformers using `cirq.TransformerLogger`, as shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "140330585db5"
   },
   "outputs": [],
   "source": [
    "context = cirq.TransformerContext(logger=cirq.TransformerLogger())\n",
    "gateset = cirq.SqrtIswapTargetGateset()\n",
    "sqrt_iswap_circuit = cirq.optimize_for_target_gateset(circuit, gateset=gateset, context=context)\n",
    "cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(circuit, sqrt_iswap_circuit)\n",
    "context.logger.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "aTNKFcPesNpy"
   },
   "source": [
    "# Summary\n",
    "Cirq provides a plethora of built-in transformers which can be composed together into useful abstractions, like `cirq.CompilationTargetGateset`, which in-turn can be serialized and can be used as a parameter in larger compilation pipelines and experiment workflows. \n",
    "\n",
    "Try using these transformers to compile your circuits and refer to the API reference docs of `cirq.TRANSFORMER` for more details. "
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "transformers.ipynb",
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
